package com.fr.lintcode;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

public class Q570ii {

	/**
	 * @param n:   An integer
	 * @param str: a string with number from 1-n in random order and miss one number
	 * @return: An integer
	 */
	int rs = 0;
	public int findMissing2(int n, String str) {
		// write your code here
		if (n <= 0 || str == null) {
			return 0;
		}
		if (n == 1) {
			return 1;
		}
		Set<Integer> filter = new HashSet<>();
		for(int i = 1; i <= n; i++) {
			filter.add(i);
		}
		int index = 0;
		search(index, filter, n, str); 
		return rs;
	}

	private void search(int index, Set<Integer> filter, int n, String str) {
		// TODO Auto-generated method stub
		if (rs > 0) {
			return;
		}
		if (filter.size() == 1 && index == str.length()) {
			for(int f : filter) {
				rs = f;
			}
			return;
		}
		int i = str.charAt(index) - '0';
		if(i == 0) {
			return;
		}
		if (i <= n) {
			if(filter.contains(i)) {
				filter.remove(i);
				search(index + 1, filter, n, str);
				filter.add(i);
			}
			if(index + 1 < str.length()) {
				i = i * 10 + str.charAt(index + 1) - '0';
				if (i <= n && filter.contains(i)) {
					filter.remove(i);
					search(index + 2, filter, n, str);
					filter.add(i);
				}
			}
		}
		
	}
	
	@Test
	public void testA() {
		int rs = findMissing2(13, "1110987654321213");
		System.out.println(rs);

	}



}
